package stdio.costa.imoca.task;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import stdio.costa.imoca.model.Postcard;

@Service
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class PostcardMakerTask {
	
	private static final Logger logger = LoggerFactory.getLogger(PostcardMakerTask.class);
	
	@Value("#{properties['postcards.maker.batch.size']}")
	private int batchSize;
	
	@PersistenceContext
	private EntityManager entityManager; 
	
	@Autowired
	@Qualifier("asyncPostcardMaker")
	private PostcardMaker postcardMaker;
	
	@SuppressWarnings("unchecked")
	@Transactional
	public void findAndMake() {
		logger.info("Finding and making postcard...");
		Query query = entityManager.createNamedQuery("Postcard.readyToPreview").setMaxResults(batchSize);
		List<Postcard> postcards = query.getResultList();
		for(Postcard postcard : postcards) {
			postcardMaker.make(postcard);
		}
		logger.info("{} postcards has been made.", postcards.size());
	}
}
